package tp.pr4.gui;

import java.awt.BorderLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;

import tp.pr4.RobotEngine;
import tp.pr4.items.Item;
import tp.pr4.items.ItemContainer;

public class RobotPanel extends JPanel {
	private RobotEngine rbt;
	private JLabel lblFuel; 
	private JLabel lblRec;	
	private TabMod tabData;
	private JTable tbl;
	private ItemContainer items;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor
	 */
	public RobotPanel(RobotEngine rbt){
		this.setBorder(new TitledBorder("Robot info"));
		this.setLayout(new BorderLayout());		
		this.rbt = rbt;		
		
		init();
	}
	
	/**
	 * builds the components of the interface
	 */
	private void init(){
		lblFuel = new JLabel("0");
		lblRec  = new JLabel("0");	
		
		JPanel panLabels = new JPanel();
		
		/*
		 * Label with fuel value
		 */
		panLabels.add(new JLabel("Fuel: "));
		panLabels.add(lblFuel);
		
		/*
		 * Label with recycled value
		 */
		panLabels.add(new JLabel("Recycled: "));
		panLabels.add(lblRec);
		
		/*
		 * creates the table 
		 */
		tabData = new TabMod(rbt.getInventory());
		tbl = new JTable(tabData);
		//tbl.setEnabled(false);//evita que la tabla sea editable
		
		/*
		 * adds the table and the labels to the layout
		 */
		this.add(tbl, BorderLayout.CENTER);	
		this.add(panLabels,BorderLayout.NORTH);
		
		refresh();
	}
	/**
	 * Refreshes Fuel, RecycledMaterial and Table
	 */
	public void refresh(){
		lblFuel.setText(rbt.getFuel()+"");
		lblRec.setText(rbt.getRecycledMaterial()+"");		
		tabData.fireTableDataChanged();
			
	}
	/**
	 * Returns current selected item in the table
	 */
	public String getSelectedItemId(){
		int rowId = tbl.getSelectedRow();
		if(rowId >= 0)
			return items.getItemInventory().get(rowId).getId();
		else
			return null;
	}
	/**
	 * Class for the table
	 * @author Mario
	 *
	 */
	private class TabMod extends AbstractTableModel{
		
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		private String[] colNames = {"Id","Description"};		
		
		public TabMod(ItemContainer its){
			items = its;
		}
		
		public String getColumnName(int col){
			return colNames[col];
		}
		
		@Override
		public int getColumnCount() {
			return 2;
		}

		@Override
		public int getRowCount() {			
			return items.numberOfItems();
		}

		@Override
		public Object getValueAt(int row, int col) {
			Item it = items.getItemInventory().get(row);
			if(col == 0){
				return it.getId();
			}else{
				return it.getDescription();
			}		
		}
		
	}
}
